<template>
  <section class="component single-adjustment">
    <data-form :model="searchModel" @onSearch="refresh">
      <template slot="inputs">
        <el-form-item
          label="账户号"
          prop="caseNumber"
          v-if="this.tagType === 'AT'"
        >
          <el-input
            v-model.trim="searchModel.caseNumber"
          ></el-input>
        </el-form-item>
        <el-form-item label="客户ID" prop="personalId" v-else>
          <el-input v-model.trim="searchModel.personalId"></el-input>
        </el-form-item>
      </template>
    </data-form>
    <el-form
      :model="model"
      :rules="rules"
      label-width="100px"
      ref="model"
      v-if="isShow"
    >
      <el-form-item
        label="账户号"
        prop="caseNumber"
        v-if="this.tagType === 'AT' && row.caseNumber"
      >
        {{ row.caseNumber }}
      </el-form-item>
      <el-form-item
        label="客户ID"
        prop="personalId"
        v-else-if="this.tagType === 'CT' && row.personalId"
      >
        {{ row.personalId }}
      </el-form-item>
      <el-form-item
        label="选择需调整的标签字段"
        prop="name"
        label-width="150px"
        ref="model"
      >
        <el-checkbox-group v-model="model.tag" v-if="tagList.length">
          <el-checkbox :label="item" v-for="item in tagList" :key="item">
            {{ item }}
          </el-checkbox>
        </el-checkbox-group>
        <div v-else>暂无数据</div>
      </el-form-item>
      <el-form-item label="调整理由" prop="note">
        <el-input
          type="textarea"
          v-model.trim="model.note"
          :maxlength="300"
          show-word-limit
        ></el-input>
      </el-form-item>
    </el-form>

    <div class="confirm-button">
      <el-button @click="emitClose">取消</el-button>
      <el-button @click="onClickCommit" :disabled="!isShow">提交审批</el-button>
    </div>
  </section>
</template>

<script lang="ts">
import { Vue, Component, Emit, Prop, Watch } from "vue-property-decorator";
import { CustomerGroupManageService } from "~/services/domain-service/customer-group-manage.service";
import { Dependencies, Layout } from "~/core/decorator";

@Component({
  components: {}
})
export default class SingleAdjustment extends Vue {
  @Dependencies(CustomerGroupManageService)
  private customerGroupManageService: CustomerGroupManageService;
  @Prop() private tagType;
  @Prop() private row;
  private model: any = {
    tag: [],
    note: ""
  };
  private rules: any = {
    note: { required: true, message: "请填写调整理由" }
  };
  private searchModel: any = {
    personalId: "",
    caseNumber: ""
  };
  private isShow: boolean = false;
  private tagList: any = [];
  private allTagList: any = [];
  private hasTagList: any = [];
  @Emit("close") private emitClose() {}
  @Emit("refreshData") private emitRefreshData() {}
  /**
   * 提交
   */
  private onClickCommit() {
    const form: any = this.$refs.model;
    if (!form) return;
    form.validate(valid => {
      if (!valid) return;

      // 用户选择的和客户原有的相同的数据去掉后，
      // 用户选择的剩下的就是新增的tag，
      // 客户原有的剩下的就是删除的tag
      const tagCopy: any = [...this.model.tag];
      const hasTagListCopy: any = [...this.hasTagList];

      this.hasTagList.forEach(v => {
        if (this.model.tag.includes(v.description)) {
          const addIndex = tagCopy.findIndex(i => i === v.description);
          tagCopy.splice(addIndex, 1);
          const delIndex = hasTagListCopy.findIndex(i => i.id === v.id);
          hasTagListCopy.splice(delIndex, 1);
        }
      });

      const addTags: any = [];
      this.allTagList.forEach(v => {
        if (tagCopy.includes(v.description)) {
          addTags.push({
            tagId: v.id,
            tagName: v.description
          });
        }
      });

      const delTags = hasTagListCopy.map(v => {
        return {
          tagId: v.id,
          tagName: v.description.replace("(现有)", "")
        };
      });

      const params = {
        addTags,
        delTags,
        note: this.model.note,
        personalId: this.searchModel.personalId,
        caseNumber: this.searchModel.caseNumber
      };
      if (this.tagType === "CT") this.customerCommit(params);
      else this.accountCommit(params);
    });
  }

  private customerCommit(params) {
    delete params.caseNumber;
    this.customerGroupManageService
      .personalSingleAdjustment(params)
      .subscribe(data => {
        this.successhandler();
      });
  }

  private accountCommit(params) {
    delete params.personalId;

    this.customerGroupManageService
      .caseSingleAdjustment(params)
      .subscribe(data => {
        this.successhandler();
      });
  }

  private successhandler() {
    this.$message.success("操作成功！");
    this.emitClose();
    this.emitRefreshData();
  }

  private refresh() {
    if (this.tagType === "CT" && !this.searchModel.personalId)
      return this.$message.error("请输入客户ID");
    if (this.tagType === "AT" && !this.searchModel.caseNumber)
      return this.$message.error("请输入账户号");
    if (this.tagType === "AT")
      this.atParamsHandler(this.searchModel.caseNumber);
    else this.ctParamsHandler(this.searchModel.personalId);
  }

  private atParamsHandler(caseNumber) {
    this.customerGroupManageService
      .getCaseTags({ caseNumber })
      .subscribe(data => {
        this.dataHandler(data);
      });
  }

  private ctParamsHandler(personalId) {
    this.customerGroupManageService
      .getPersonalTags({ personalId })
      .subscribe(data => {
        this.dataHandler(data);
      });
  }

  private dataHandler(data) {
    this.isShow = true;
    this.hasTagList = data;
    // 已有标签展示现有
    this.allTagList.forEach(i => {
      this.hasTagList.forEach(v => {
        if (v.description === i.description) {
          i.description = `${i.description}(现有)`;
          v.description = `${v.description}(现有)`;
        }
      });
    });
    this.tagList = this.allTagList.map(v => v.description);
    const arr = data.map(v => v.description);
    this.model.tag = [...arr];
  }

  private getAllCTList(data) {
    this.customerGroupManageService
      .getEffectTags({ tagLevel: data })
      .subscribe(data => {
        data.map(v => {
          this.allTagList = data;
          this.tagList = data.map(v => v.description);
        });
      });
  }
}
</script>
